import React, { useState } from 'react';
import { 
  Typography, 
  Grid, 
  Alert, 
  AlertTitle,
  Tabs,
  Tab,
  Chip,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tooltip,
  IconButton,
  Box,
  InputAdornment,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableBody,
  TableCell,
  useTheme
} from '@mui/material';

// Icons
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import RefreshIcon from '@mui/icons-material/Refresh';
import InfoIcon from '@mui/icons-material/Info';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';

// Router
import { useNavigate } from 'react-router-dom';

// Styled Components
import {
  StyledPaper,
  StyledAppButton,
  StyledTable,
  paperSX,
  tableSX
} from 'components/objects/StyledComponents';

// Mock data imports
import { 
  mockSubscriptionInfo,
  generateMockCustomers 
} from 'data/mockTrialData';

// Styled components specific to this page
const StyledTableCell = ({ children, ...props }) => {
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';
  
  return (
    <TableCell 
      {...props}
      sx={{
        fontWeight: 'bold',
        backgroundColor: isDarkMode ? 'rgba(0, 0, 0, 0.2)' : 'rgba(223, 227, 238, 0.5)',
        color: isDarkMode ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 2, 3, 0.9)'
      }}
    >
      {children}
    </TableCell>
  );
};

const LogViewerBox = ({ children }) => {
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';
  
  return (
    <Box
      sx={{
        p: 2,
        backgroundColor: isDarkMode ? 'rgba(0, 0, 0, 0.2)' : 'rgba(245, 247, 250, 0.8)',
        borderRadius: 1,
        maxHeight: '200px',
        overflowY: 'auto',
        ...(!isDarkMode && { boxShadow: 'inset 0px 0px 4px rgba(0, 0, 0, 0.05)' }),
        ...(isDarkMode && { border: '1px solid rgba(0, 255, 242, 0.1)' })
      }}
    >
      {children}
    </Box>
  );
};

const ExpandedInfoBox = ({ children }) => {
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';
  
  return (
    <Box
      sx={{
        p: 2,
        backgroundColor: isDarkMode ? 'rgba(0, 0, 0, 0.1)' : 'rgba(245, 247, 250, 0.5)',
        borderBottom: isDarkMode ? '1px solid rgba(0, 255, 242, 0.1)' : '1px solid rgba(0, 0, 0, 0.1)'
      }}
    >
      {children}
    </Box>
  );
};

/**
 * TrialComponent
 * 
 * Displays trial-specific information and a mock version of the customer subscription data
 * for users who are on a trial plan.
 */
const TrialComponent = ({ user }) => {
  const navigate = useNavigate();
  const [tabValue, setTabValue] = useState(0);
  const [expandedCustomer, setExpandedCustomer] = useState(null);
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';
  
  // Get mock data
  const subscriptionInfo = mockSubscriptionInfo;
  const customers = generateMockCustomers();
  
  // Calculate days remaining in trial
  const calculateTrialDaysRemaining = () => {
    if (user?.account?.trialPeriodEndsAt) {
      const trialEnd = new Date(user.account.trialPeriodEndsAt);
      const today = new Date();
      const diffTime = trialEnd - today;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays > 0 ? diffDays : 0;
    }
    return 0;
  };
  
  const trialDaysRemaining = calculateTrialDaysRemaining();
  
  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };
  
  // Handle customer expand
  const handleExpandCustomer = (customerId) => {
    setExpandedCustomer(expandedCustomer === customerId ? null : customerId);
  };
  
  // Mock function
  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text);
  };
  
  // Handle upgrade click
  const handleUpgradeClick = () => {
    navigate('/plan');
  };
  
  // Format the trial end date
  const formatTrialEndDate = () => {
    if (user?.account?.trialPeriodEndsAt) {
      return new Date(user.account.trialPeriodEndsAt).toLocaleString();
    }
    return 'unknown';
  };
  
  return (
    <Grid container spacing={3}>
      <Grid item xs={12}>
        <Alert 
          severity="info" 
          variant="filled"
          action={
            <StyledAppButton 
              darkMode={isDarkMode}
              color="inherit" 
              size="small" 
              variant="outlined"
              startIcon={<ShoppingCartIcon />}
              onClick={handleUpgradeClick}
            >
              Upgrade Now
            </StyledAppButton>
          }
          sx={{ borderRadius: 2, mb: 3 }}
        >
          <AlertTitle>Trial Account</AlertTitle>
          You are currently on a trial plan. 
          {trialDaysRemaining > 0 ? (
            <strong> You have {trialDaysRemaining} days remaining in your trial.</strong>
          ) : (
            <strong> Your trial has expired. Please upgrade to continue accessing all features.</strong>
          )}
        </Alert>
      </Grid>
      
      <Grid item xs={12}>
        <StyledPaper darkMode={isDarkMode}>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h5">
              Customer Data Management 
              <Chip label="TRIAL VERSION" color="warning" size="small" sx={{ ml: 2 }} />
            </Typography>
          </Box>
          
          <StyledPaper darkMode={isDarkMode} sx={{ mb: 3, p: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
              <Typography variant="h6">
                Subscription Info
              </Typography>
              <StyledAppButton 
                darkMode={isDarkMode}
                variant="contained"
                color="primary"
                startIcon={<RefreshIcon />}
                disabled={true}
              >
                Refresh Data
              </StyledAppButton>
            </Box>
            
            <Grid container spacing={2}>
              <Grid item xs={6} sm={3}>
                <Typography variant="subtitle2">Total Records:</Typography>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Typography variant="h6" fontWeight="bold">
                    {subscriptionInfo.totalRecords}
                  </Typography>
                  <Tooltip title="Trial accounts are limited to 5 sample records">
                    <IconButton size="small">
                      <InfoIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </Box>
              </Grid>
              
              <Grid item xs={6} sm={3}>
                <Typography variant="subtitle2">New Records Added:</Typography>
                <Typography variant="h6" fontWeight="bold">
                  {subscriptionInfo.newRecordsAdded}
                </Typography>
              </Grid>
              
              <Grid item xs={6} sm={3}>
                <Typography variant="subtitle2">Oldest Record:</Typography>
                <Typography variant="body2">
                  {subscriptionInfo.oldestRecord 
                    ? new Date(subscriptionInfo.oldestRecord).toLocaleDateString() 
                    : 'N/A'}
                </Typography>
              </Grid>
              
              <Grid item xs={6} sm={3}>
                <Typography variant="subtitle2">Newest Record:</Typography>
                <Typography variant="body2">
                  {subscriptionInfo.newestRecord 
                    ? new Date(subscriptionInfo.newestRecord).toLocaleDateString() 
                    : 'N/A'}
                </Typography>
              </Grid>
            </Grid>
            
            <Box sx={{ mt: 2 }}>
              <Chip 
                label={`File ID: ${subscriptionInfo.fileIdentifier}`} 
                variant="outlined" 
                color="primary"
                size="small"
              />
            </Box>
          </StyledPaper>
          
          <StyledPaper darkMode={isDarkMode} sx={{ mb: 3 }}>
            <Tabs 
              value={tabValue} 
              onChange={handleTabChange}
              indicatorColor="primary"
              textColor="primary"
              variant="fullWidth"
              sx={{ borderBottom: isDarkMode ? '1px solid rgba(0, 255, 242, 0.25)' : '1px solid rgba(0, 0, 0, 0.1)' }}
            >
              <Tab label="Basic Information" />
              <Tab label="Billing Details" />
              <Tab label="Shipping Details" />
              <Tab label="Account Info" />
            </Tabs>
            
            <TableContainer sx={{ mt: 2 }}>
              {/* Basic Information Tab */}
              {tabValue === 0 && (
                <StyledTable darkMode={isDarkMode}>
                  <TableHead>
                    <TableRow>
                      <StyledTableCell>ID</StyledTableCell>
                      <StyledTableCell>Customer ID</StyledTableCell>
                      <StyledTableCell>Name</StyledTableCell>
                      <StyledTableCell>Email</StyledTableCell>
                      <StyledTableCell>Phone</StyledTableCell>
                      <StyledTableCell>Fax</StyledTableCell>
                      <StyledTableCell>Member Since</StyledTableCell>
                      <StyledTableCell>Last Updated</StyledTableCell>
                      <StyledTableCell>Actions</StyledTableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {customers.map(customer => (
                      <React.Fragment key={customer.cID}>
                        <TableRow>
                          <TableCell>{customer.cID}</TableCell>
                          <TableCell>{customer.cString}</TableCell>
                          <TableCell>
                            <Tooltip title={customer.cBillCompany ? `Company: ${customer.cBillCompany}` : ""}>
                              <span>{customer.cBillFname} {customer.cBillLname}</span>
                            </Tooltip>
                          </TableCell>
                          <TableCell>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              {customer.cEmail}
                              <IconButton size="small" onClick={() => copyToClipboard(customer.cEmail)}>
                                <ContentCopyIcon fontSize="small" />
                              </IconButton>
                            </Box>
                          </TableCell>
                          <TableCell>{customer.cPhone}</TableCell>
                          <TableCell>{customer.cFax || 'N/A'}</TableCell>
                          <TableCell>
                            {new Date(customer.cDateSince).toLocaleDateString()}
                          </TableCell>
                          <TableCell>
                            {new Date(customer.cUpdateDate).toLocaleDateString()}
                          </TableCell>
                          <TableCell>
                            <IconButton 
                              size="small" 
                              onClick={() => handleExpandCustomer(customer.cID)}
                              color={expandedCustomer === customer.cID ? "primary" : "default"}
                            >
                              <ExpandMoreIcon />
                            </IconButton>
                          </TableCell>
                        </TableRow>
                        
                        {expandedCustomer === customer.cID && (
                          <TableRow>
                            <TableCell colSpan={9} sx={{ p: 0 }}>
                              <ExpandedInfoBox>
                                <Typography variant="subtitle2" fontWeight="bold" mb={1}>
                                  Additional Information
                                </Typography>
                                <Grid container spacing={2}>
                                  <Grid item xs={12} sm={4}>
                                    <Typography variant="subtitle2">Reference:</Typography>
                                    <Typography>{customer.cMemo || 'N/A'}</Typography>
                                  </Grid>
                                  <Grid item xs={12} sm={4}>
                                    <Typography variant="subtitle2">How Found:</Typography>
                                    <Typography>{customer.cHow || 'N/A'}</Typography>
                                  </Grid>
                                  <Grid item xs={12} sm={4}>
                                    <Typography variant="subtitle2">Wholesale Discount:</Typography>
                                    <Typography>
                                      {customer.cWholesaleDiscount ? `${customer.cWholesaleDiscount}%` : 'None'}
                                    </Typography>
                                  </Grid>
                                </Grid>
                              </ExpandedInfoBox>
                            </TableCell>
                          </TableRow>
                        )}
                      </React.Fragment>
                    ))}
                  </TableBody>
                </StyledTable>
              )}
              
              {/* Billing Details Tab */}
              {tabValue === 1 && (
                <StyledTable darkMode={isDarkMode}>
                  <TableHead>
                    <TableRow>
                      <StyledTableCell>ID</StyledTableCell>
                      <StyledTableCell>Company</StyledTableCell>
                      <StyledTableCell>Name</StyledTableCell>
                      <StyledTableCell>Address</StyledTableCell>
                      <StyledTableCell>City</StyledTableCell>
                      <StyledTableCell>State/Province</StyledTableCell>
                      <StyledTableCell>Postal Code</StyledTableCell>
                      <StyledTableCell>County</StyledTableCell>
                      <StyledTableCell>Country</StyledTableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {customers.map(customer => (
                      <TableRow key={customer.cID}>
                        <TableCell>{customer.cID}</TableCell>
                        <TableCell>{customer.cBillCompany || 'N/A'}</TableCell>
                        <TableCell>{customer.cBillFname} {customer.cBillLname}</TableCell>
                        <TableCell>
                          {customer.cBillAddress1}
                          {customer.cBillAddress2 && (
                            <Typography variant="body2" sx={{ opacity: 0.7 }}>
                              {customer.cBillAddress2}
                            </Typography>
                          )}
                        </TableCell>
                        <TableCell>{customer.cBillCity}</TableCell>
                        <TableCell>{customer.cBillState || 'N/A'}</TableCell>
                        <TableCell>{customer.cBillZip}</TableCell>
                        <TableCell>{customer.bill_county || 'N/A'}</TableCell>
                        <TableCell>{customer.cBillCountry}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </StyledTable>
              )}
              
              {/* Shipping Details Tab */}
              {tabValue === 2 && (
                <StyledTable darkMode={isDarkMode}>
                  <TableHead>
                    <TableRow>
                      <StyledTableCell>ID</StyledTableCell>
                      <StyledTableCell>Same as Billing</StyledTableCell>
                      <StyledTableCell>Company</StyledTableCell>
                      <StyledTableCell>Name</StyledTableCell>
                      <StyledTableCell>Address</StyledTableCell>
                      <StyledTableCell>City</StyledTableCell>
                      <StyledTableCell>State/Province</StyledTableCell>
                      <StyledTableCell>Postal Code</StyledTableCell>
                      <StyledTableCell>County</StyledTableCell>
                      <StyledTableCell>Country</StyledTableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {customers.map(customer => (
                      <TableRow key={customer.cID}>
                        <TableCell>{customer.cID}</TableCell>
                        <TableCell>
                          {customer.billEqualShip === '1' ? (
                            <Chip size="small" label="Yes" color="success" />
                          ) : (
                            <Chip size="small" label="No" color="default" />
                          )}
                        </TableCell>
                        <TableCell>{customer.cShipCompany || 'N/A'}</TableCell>
                        <TableCell>{customer.cShipFname} {customer.cShipLname}</TableCell>
                        <TableCell>
                          {customer.cShipAddress1}
                          {customer.cShipAddress2 && (
                            <Typography variant="body2" sx={{ opacity: 0.7 }}>
                              {customer.cShipAddress2}
                            </Typography>
                          )}
                        </TableCell>
                        <TableCell>{customer.cShipCity}</TableCell>
                        <TableCell>{customer.cShipState || 'N/A'}</TableCell>
                        <TableCell>{customer.cShipZip}</TableCell>
                        <TableCell>{customer.ship_county || 'N/A'}</TableCell>
                        <TableCell>{customer.cShipCountry}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </StyledTable>
              )}
              
              {/* Account Info Tab */}
              {tabValue === 3 && (
                <StyledTable darkMode={isDarkMode}>
                  <TableHead>
                    <TableRow>
                      <StyledTableCell>ID</StyledTableCell>
                      <StyledTableCell>Email</StyledTableCell>
                      <StyledTableCell>Password Status</StyledTableCell>
                      <StyledTableCell>Password Hint</StyledTableCell>
                      <StyledTableCell>Account Status</StyledTableCell>
                      <StyledTableCell>Last Error</StyledTableCell>
                      <StyledTableCell>Lock Time</StyledTableCell>
                      <StyledTableCell>Lock IP</StyledTableCell>
                      <StyledTableCell>Lock Count</StyledTableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {customers.map(customer => (
                      <TableRow key={customer.cID}>
                        <TableCell>{customer.cID}</TableCell>
                        <TableCell>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            {customer.cEmail}
                            <IconButton size="small" onClick={() => copyToClipboard(customer.cEmail)}>
                              <ContentCopyIcon fontSize="small" />
                            </IconButton>
                          </Box>
                        </TableCell>
                        <TableCell>
                          {customer.cPass ? (
                            <Chip size="small" label="Set" color="success" />
                          ) : (
                            <Chip size="small" label="Not Set" color="error" />
                          )}
                        </TableCell>
                        <TableCell>{customer.cPassHint || 'N/A'}</TableCell>
                        <TableCell>
                          {customer.cLocknum && parseInt(customer.cLocknum) > 0 ? (
                            <Chip size="small" label="Locked" color="error" />
                          ) : (
                            <Chip size="small" label="Active" color="success" />
                          )}
                        </TableCell>
                        <TableCell>{customer.cLasterr || 'None'}</TableCell>
                        <TableCell>{customer.cLocktime || 'N/A'}</TableCell>
                        <TableCell>{customer.cLockip || 'N/A'}</TableCell>
                        <TableCell>{customer.cLocknum || '0'}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </StyledTable>
              )}
            </TableContainer>
          </StyledPaper>
          
          <StyledPaper darkMode={isDarkMode} sx={{ mb: 3 }}>
            <Accordion elevation={0} sx={{ bgcolor: 'transparent' }}>
              <AccordionSummary 
                expandIcon={<ExpandMoreIcon />}
                sx={{ 
                  p: 0, 
                  bgcolor: 'transparent', 
                  '&:hover': { bgcolor: 'transparent' },
                  '&.Mui-expanded': { bgcolor: 'transparent' }
                }}
              >
                <Typography variant="h6">
                  System Logs
                </Typography>
              </AccordionSummary>
              <AccordionDetails sx={{ p: 0, pt: 1 }}>
                <LogViewerBox>
                  <Typography variant="body2" color="textSecondary" fontFamily="monospace">
                    {new Date().toISOString()} [INFO] Trial data loaded successfully<br/>
                    {new Date().toISOString()} [INFO] Sample records: 5<br/>
                    {new Date().toISOString()} [INFO] User: {user?.email || 'unknown'}<br/>
                    {new Date().toISOString()} [INFO] Trial period ends: {formatTrialEndDate()}<br/>
                    {new Date().toISOString()} [INFO] Mock data presented for trial preview purposes<br/>
                    {new Date().toISOString()} [WARN] Limited functionality in trial mode<br/>
                    {new Date().toISOString()} [INFO] To unlock full features, please upgrade your subscription
                  </Typography>
                </LogViewerBox>
              </AccordionDetails>
            </Accordion>
          </StyledPaper>
          
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4, mb: 2 }}>
            <StyledAppButton 
              darkMode={isDarkMode}
              variant="contained" 
              color="primary" 
              size="large"
              startIcon={<ShoppingCartIcon />}
              onClick={handleUpgradeClick}
              sx={{ py: 1.5, px: 4 }}
            >
              Upgrade to Access Full Features
            </StyledAppButton>
          </Box>
        </StyledPaper>
      </Grid>
    </Grid>
  );
};



export default TrialComponent;